import { NForm } from "naive-ui";
import { getSlotsDom } from "../utils";
import type { FormProps, FormInst } from "naive-ui";
import type { HTMLAttributes } from "vue";
import type { BaseComponentType } from "../types";
export type FormFactoryConstructorType = {
  props?: FormProps;
  attrs?: HTMLAttributes;
  defaultSlot?: BaseComponentType;
};
export class FormFactory {
  private attrs: HTMLAttributes = {};
  private props: FormProps = {};
  private defaultSlot: BaseComponentType = null;
  private domRef: FormInst | null = null;

  constructor(data?: FormFactoryConstructorType) {
    if (data?.props) this.setProps(data.props);
    if (data?.attrs) this.setAttrs(data.attrs);
    if (data?.defaultSlot) this.setDefault(data.defaultSlot);
  }
  setAttrs(attrs: HTMLAttributes) {
    this.attrs = attrs;
    return this;
  }
  setProps(props: FormProps) {
    this.props = props;
    return this;
  }
  setDefault(component: BaseComponentType) {
    this.defaultSlot = component;
    return this;
  }
  validate() {
    this.domRef?.validate();
  }
  restoreValidation() {
    this.domRef?.restoreValidation();
  }
  create() {
    return (
      <NForm
        ref={(el: HTMLElement) => {
          this.domRef = el as unknown as FormInst;
        }}
        {...this.attrs}
        {...this.props}
      >
        {{
          default: () => getSlotsDom(this.defaultSlot),
        }}
      </NForm>
    );
  }
}
